<?php
class Backend_Medialib_Controller extends Backend_Controller{ 
    
    public function indexAction(){
  
        $resource = Resource::getInstance();

        $media = Model_Medialib::getInstance();
        $media->includeScripts();
        $this->_resource->addJs('/js/app/system/crud/'.strtolower($this->_module).'.js'  , 4);

         $this->_resource->addInlineJs('
        	var canEdit = '.((boolean)$this->_user->canEdit($this->_module)).';
        	var canDelete = '.((boolean)$this->_user->canDelete($this->_module)).';
        ');
    }
    
    public function listAction(){
    
        $pager = Request::post('pager', 'array', array());
        $filter = Request::post('filter', 'array', array());
        $query = Request::post('search', 'string', false);
     
        
        $media = Model_Medialib::getInstance();
        $data = $media->getListVc($pager , $filter, $query,'*','user_name');
        
        $conf = $media->getConfig();
    
        if(!empty($data)){
            foreach ($data as $k=>&$v){
                if($v['type'] == 'image'){
                    $v['icon'] = str_replace($v['ext'],'-icon'.$v['ext'] , $v['path']);
                    $v['thumbnail'] = str_replace($v['ext'],'-thumbnail'.$v['ext'] , $v['path']);
                    $v['medium'] = str_replace($v['ext'],'-medium'.$v['ext'] , $v['path']);
                    $v['large'] = str_replace($v['ext'],'-large'.$v['ext'] , $v['path']);
                    $v['small'] = str_replace($v['ext'],'-small'.$v['ext'] , $v['path']);
                     $v['mini'] = str_replace($v['ext'],'-mini'.$v['ext'] , $v['path']);
                }else{
                    $v['icon'] ='/i/unknown.png';
                    $v['thumbnail']='/i/unknown.png';
                }
            } unset($v);
        }
        
        
        $result = array(
            'success'=>true,
            'count'=>$media->getCount($pager , $filter , $query),
            'data'=>$data
        );
         Response::jsonArray($result);
    }
    
    public function uploadAction()
    {
        if(!User_Admin::getInstance()->canEdit($this->_module))
            Response::jsonError($this->_lang->CANT_MODIFY);

        $docRoot = $this->_configMain->get('docroot');    
            
        $mediaCfg = Model_Medialib::getInstance()->getConfig();                 
        $path = $this->_configMain->get('uploads') . date('Y').'/'.date('m').'/'.date('d').'/';   
    
		if (!is_dir($path))
			if (!@mkdir($path, 0775, true))
	             Response::jsonError($this->_lang->CANT_WRITE_FS);
     
        $files = Request::files();
    
        $uploader = new Upload($mediaCfg->__toArray());
        $mediaModel = Model_Medialib::getInstance();
        
        if(empty($files))
            Response::jsonError($this->_lang->NOT_UPLOADED);
            
        $uploaded = $uploader->start($files, $path);
        
        if(empty($uploaded))    
            Response::jsonError($this->_lang->NOT_UPLOADED);
               
        $data = array();
        
        foreach ($uploaded as $k=>&$v)
        {
              $path = str_replace($docRoot,'',$v['path']);
              $id =  $mediaModel->addItem($v['title'] , $path , $v['size'] , $v['type'] ,$v['ext']);   

               if($v['type'] == 'image'){
                   $thumb = str_replace($docRoot,'',$v['thumb']);
               }else{
                    $thumb  = '/i/unknown.png' ;
               }
               
               $data[] = array(
                   'id'=>$id,
				   'type'=>$v['type'],
				   'url'=>$this->_configMain->get('url') . $path,
				   'title'=>basename($v['path']),
                   'size'=>number_format(($v['size']/1024/1024),3).'mb',
                   'thumb'=>$thumb
               );
         }
         
         if(!Request::post('uploadify','integer',0)){
             Response::jsonSuccess($data);
         }else{
             echo 1;exit();
         }
    }
    
    public function cropAction()
    {
        if(!User_Admin::getInstance()->canEdit($this->_module))
            Response::jsonError($this->_lang->CANT_MODIFY);
                   
            $id = Request::post('id', 'integer', false);
            $x = Request::post('x', 'integer', false);      
            $y = Request::post('y', 'integer', false);         
            $w = Request::post('w', 'integer', false);        
            $h = Request::post('h', 'integer', false);       
            $type = Request::post('type','string', false)  ;
            
            if(!$id || !$w || !$h || !$type){
                Response::jsonError($this->_lang->WRONG_REQUEST);
            }
            
            $mediaModel = Model_Medialib::getInstance();
            $item = $mediaModel->getItem($id);
            
            if(!$item){
                Response::jsonError(LONG_WRONG_REQUEST);
            }
            
            if($mediaModel->cropAndResize($item, $x, $y, $w, $h , $type))
            {
                $mediaModel->updateModifyDate($id);
                $mediaModel->markCroped($id);
                Response::jsonSuccess();
            }else{
                Response::jsonError($this->_lang->CANT_EXEC);
            }
    }
    

    public function removeAction(){

         if(!User_Admin::getInstance()->canDelete($this->_module))
               Response::jsonError($this->_lang->CANT_DELETE);
     
         $id = Request::post('id','integer', false);
           
          if(!$id)
               Response::jsonError($this->_lang->WRONG_REQUEST);
               
         $media= Model_Medialib::getInstance();
         if($media->remove($id))
             Response::jsonSuccess();
         else
            Response::jsonError($this->_lang->WRONG_REQUEST);
    }
     
    public function updateAction(){

        if(!User_Admin::getInstance()->canEdit($this->_module))
            Response::jsonError($this->_lang->CANT_MODIFY);
                   
           $id = Request::post('id','integer', false);
           
           if(!$id)
               Response::jsonError($this->_lang->WRONG_REQUEST);
    
            $fields = array('title','alttext','caption','description');
    
            $data = array();
            
            foreach ($fields as $v){
                if($v=='caption')
                  $data[$v] = Request::post($v,'raw','');
                else
                    $data[$v] = Request::post($v,'string','');
            }
            
            if(!strlen($data['title']))
                Response::jsonError($this->_lang->FILL_FORM , array('title'=>$this->_lang->CANT_BE_EMPTY));
                
            $media = Model_Medialib::getInstance();
            
            if($media->update($id , $data))
                Response::jsonSuccess();
            else
                Response::jsonError($this->_lang->CANT_EXEC);   
    }
    
    public function getitemAction()
    {

        $id = Request::post('id','integer',false);
        
        if(!$id)
            Response::jsonError();
            
         $item =Model_Medialib::getInstance()->getItem($id) ;
           if($item['type'] == 'image'){
                    $item['icon'] = str_replace($item['ext'],'-icon'.$item['ext'] , $item['path']);
                    $item['thumbnail'] = str_replace($item['ext'],'-thumbnail'.$item['ext'] , $item['path']);
                    $item['medium'] = str_replace($item['ext'],'-medium'.$item['ext'] , $item['path']);
                    $item['large'] = str_replace($item['ext'],'-large'.$item['ext'] , $item['path']);
           }
            
         Response::jsonSuccess($item);   
    }
}